package io.github.shenbinglife.springboot2.layui.admin.dao;

import io.github.shenbinglife.springboot2.layui.admin.entity.User;
import io.github.shenbinglife.springboot2.layui.common.jpa.IBaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface UserDao extends IBaseRepository<User, Long> {
    @Modifying
    @Query("update User c set c.state = :state WHERE c.id = :id")
    void updateStateById(Long id, User.UserState state);

    @Query(value = "select u.password from tbl_sys_user u where u.id = :userId", nativeQuery = true)
    String getPasswordByUserId(Long userId);

    User findByAccount(String account);

    @Modifying
    @Query(value = "update tbl_sys_user u set u.password = :password where u.id = :id", nativeQuery = true)
    void updatePassword(Long id, String password);

    @Query("select distinct u from User u " +
            " left join OrgUserRelation orgRelation on orgRelation.userId=u.id " +
            " left join Org org on org.id=orgRelation.orgId" +
            " left join RoleUserRelation rr on rr.userId=u.id" +
            " left join Role role on role.id=rr.roleId" +
            " where (:name is NULL or :name = '' or u.name=:name)" +
            " and  (:keyword is NULL or :keyword = '' or u.name like CONCAT('%',:keyword,'%') or u.account like CONCAT('%',:keyword,'%') )" +
            " and  (:orgName is NULL or :orgName = '' or org.name=:orgName)" +
            " and  (:roleName is NULL or :roleName = '' or role.name=:roleName)" +
            " and  (:orgId is NULL or :orgId = '' or org.id=:orgId)" +
            " and  (:roleId is NULL or :roleId = '' or role.id=:roleId)" +
            " and  (:notOrgId is NULL or :notOrgId = '' or not exists (select subOrgRelation from OrgUserRelation subOrgRelation where subOrgRelation.orgId =:notOrgId and subOrgRelation.userId=u.id) )" +
            " and  (:notRoleId is NULL or :notRoleId = '' or not exists (select subRoleUserRelation from RoleUserRelation subRoleUserRelation where subRoleUserRelation.roleId =:notRoleId and subRoleUserRelation.userId=u.id) )" +
            " and  (:mobilePhone is NULL or :mobilePhone = '' or u.mobilePhone=:mobilePhone)")
    Page<User> findUsersWithPagination(String keyword, String name, String orgName, String roleName, String orgId,
                                       String roleId,
                                       String notOrgId,
                                       String notRoleId,
                                       String mobilePhone, Pageable pageable);

}
